"""
Azure OCR 服务封装
提供图片文字识别功能
"""

import os
import json
import logging
import base64
import requests
from typing import Dict, Any, Optional

logger = logging.getLogger(__name__)


class AzureOCRService:
    """Azure OCR 服务类"""

    def __init__(self):
        self.endpoint = os.getenv('AZURE_OCR_ENDPOINT', '')
        self.api_key = os.getenv('AZURE_OCR_KEY', '')
        self.api_version = "2022-08-31"

        if not self.endpoint or not self.api_key:
            logger.warning("Azure OCR not configured, using mock OCR")

    def recognize_text(self, image_data: str) -> Dict[str, Any]:
        """
        识别图片中的文字

        Args:
            image_data: base64 编码的图片数据

        Returns:
            识别结果字典
        """
        try:
            if not self.endpoint or not self.api_key:
                # 返回模拟结果
                return self._get_mock_ocr_result()

            # 构建请求
            url = f"{self.endpoint}/computervision/imageanalysis:analyze"
            params = {
                'api-version': self.api_version,
                'features': 'read'
            }

            headers = {
                'Ocp-Apim-Subscription-Key': self.api_key,
                'Content-Type': 'application/json'
            }

            data = {
                "url": f"data:image/jpeg;base64,{image_data}"
            }

            # 发送请求
            response = requests.post(url, headers=headers, params=params, json=data, timeout=30)

            if response.status_code == 200:
                result = response.json()
                return self._parse_ocr_response(result)
            else:
                logger.error(f"Azure OCR API error: {response.status_code}")
                return self._get_error_result(f"API调用失败: {response.status_code}")

        except Exception as e:
            logger.error(f"OCR recognition failed: {e}")
            return self._get_error_result(str(e))

    def _parse_ocr_response(self, response: Dict[str, Any]) -> Dict[str, Any]:
        """
        解析 Azure OCR 响应

        Args:
            response: Azure API 响应

        Returns:
            结构化的识别结果
        """
        try:
            # 提取识别的文字
            read_result = response.get('readResult', {})
            lines = []

            for page in read_result.get('pages', []):
                for line in page.get('lines', []):
                    text = line.get('content', '')
                    lines.append(text)

            full_text = ' '.join(lines)

            # 使用正则表达式提取关键信息
            import re

            # 提取金额
            amount_pattern = r'[\$¥￥]?(\d+(?:,\d{3})*(?:\.\d{2})?)'
            amount_match = re.search(amount_pattern, full_text)
            amount = amount_match.group(1) if amount_match else "0.00"

            # 提取订单号
            order_pattern = r'订单[号:]*([A-Z0-9]+)'
            order_match = re.search(order_pattern, full_text, re.IGNORECASE)
            order_id = order_match.group(1) if order_match else "UNKNOWN"

            # 提取日期
            date_pattern = r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})'
            date_match = re.search(date_pattern, full_text)
            date = date_match.group(1) if date_match else "UNKNOWN"

            return {
                "success": True,
                "amount": amount,
                "order_id": order_id,
                "date": date,
                "full_text": full_text[:500],  # 限制长度
                "confidence": 0.95  # 模拟置信度
            }

        except Exception as e:
            logger.error(f"Failed to parse OCR response: {e}")
            return self._get_error_result("响应解析失败")

    def _get_mock_ocr_result(self) -> Dict[str, Any]:
        """
        获取模拟 OCR 结果（用于演示）

        Returns:
            模拟识别结果
        """
        return {
            "success": True,
            "amount": "299.00",
            "order_id": "ORD20250401",
            "date": "2024-04-01",
            "full_text": "发票 示例公司 订单号: ORD20250401 金额: ¥299.00 日期: 2024-04-01",
            "confidence": 0.90
        }

    def _get_error_result(self, error_msg: str) -> Dict[str, Any]:
        """
        获取错误结果

        Args:
            error_msg: 错误信息

        Returns:
            错误结果字典
        """
        return {
            "success": False,
            "error": error_msg,
            "amount": "0.00",
            "order_id": "UNKNOWN",
            "date": "UNKNOWN",
            "full_text": "",
            "confidence": 0.0
        }


# 全局 OCR 服务实例
_ocr_service = None


def get_ocr_service() -> AzureOCRService:
    """获取 OCR 服务实例"""
    global _ocr_service
    if _ocr_service is None:
        _ocr_service = AzureOCRService()
    return _ocr_service


async def ocr_image(image_b64: str) -> Dict[str, Any]:
    """
    异步 OCR 图片识别

    Args:
        image_b64: base64 编码的图片数据

    Returns:
        识别结果字典
    """
    service = get_ocr_service()
    return service.recognize_text(image_b64)


def extract_invoice_info(text: str) -> Dict[str, str]:
    """
    从识别的文字中提取发票信息

    Args:
        text: 识别的文字内容

    Returns:
        提取的信息字典
    """
    import re

    # 预定义的提取规则
    patterns = {
        "amount": r'[\$¥￥]?(\d+(?:,\d{3})*(?:\.\d{2})?)',
        "order_id": r'订单[号:]*([A-Z0-9]+)',
        "date": r'(\d{4}[-/]\d{1,2}[-/]\d{1,2})',
        "company": r'公司[:]*([^\n\r]+)',
        "tax_id": r'税号[:]*([A-Z0-9]+)'
    }

    result = {}
    for key, pattern in patterns.items():
        match = re.search(pattern, text, re.IGNORECASE)
        result[key] = match.group(1) if match else "UNKNOWN"

    return result
